//
//  EmyoneHttpService.m
//  emyone
//
//  Created by LiangLigeng on 13-12-9.
//  Copyright (c) 2013年 LiangLigeng. All rights reserved.
//

#import "HttpService.h"

//#define BASE_URL @"http://58.42.247.48:8006/GovermentService/"
//#define BASE_URL @"http://222.85.136.55:8033/GovermentService/"
#define BASE_URL @"http://219.151.1.147:8002/Api/Home/"

@implementation HttpService

+(ASIFormDataRequest *)requestWithUrl:(NSString*)urlString
                               params:(NSMutableDictionary*) params
                           httpMethod:(NSString*)httpMethod
                        completeBlock:(RequestFinishBlock)block{
    
    urlString =[BASE_URL stringByAppendingFormat:@"%@",urlString];
    //NSDictionary *emyoneInfo=[defaults objectForKey:@"EmyoneAuthData"];
    //get请求参数
    NSComparisonResult compareRet1=[httpMethod caseInsensitiveCompare:@"GET"];
    if (compareRet1==NSOrderedSame) {
        NSMutableString *paramsString=[NSMutableString string];
        NSArray *allkeys=[params allKeys];
        for (int i=0; i<params.count; i++) {
            NSString *key=[allkeys objectAtIndex:i];
            id value=[params objectForKey:key];
            [paramsString appendFormat:@"%@=%@",key,value];
            if (i<params.count-1) {
                [paramsString appendString:@"&"];
            }
            
        }
        if (paramsString.length>0) {
               urlString= [urlString stringByAppendingFormat:@"&%@",paramsString];
        }
        NSLog(@"%@" ,urlString);
    }
    
    NSURL *url=[NSURL URLWithString:urlString];
    __block ASIFormDataRequest *requst=[ASIFormDataRequest requestWithURL:url];
    [requst setTimeOutSeconds:20];
    [requst setRequestMethod:httpMethod];
    //[requst addRequestHeader:@"Accept" value:@"application/json"];
    //post请求参数
    NSComparisonResult compareRet=[httpMethod caseInsensitiveCompare:@"POST"];
    if (compareRet==NSOrderedSame) {
        
        NSArray *allkeys=[params allKeys];
        for (int i=0; i<params.count; i++) {
            NSString *key=[allkeys objectAtIndex:i];
            id value=[params objectForKey:key];
            if ([value isKindOfClass:[NSData class]]) {
                [requst addData:value forKey:key];
            }else{
                [requst addPostValue:value forKey:key];
            }
        }
    }
    
    [requst setCompletionBlock:^{
        NSData *data=requst.responseData;
        id result=nil;
        //result=data;
        result= [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
       
        if (block!=nil) {
            block(result);
        }
        
    }];
    [requst setFailedBlock:^
    {
        NSError *error=[requst error];
        
        //NSData *data=requst.responseData;
        if (block!=nil) {
            block(nil);
            //block(error.userInfo);
        }
    }];
    [requst startAsynchronous];
    return requst;
}
@end
